import { BookModel } from '../../models/book.js'
import { LikeModel } from '../../models/like.js'
const bookModel = new BookModel()
const likeModel = new LikeModel()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments:[],
    book:null,
    likeCount: 0,
    likeStatus: false,
    posting:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 微信自带显示loading
    wx.showLoading()
    const bid = options.bid
    const detail = bookModel.getDetail(bid)
    const comments = bookModel.getComments(bid)
    const likeStatus = bookModel.getLikeStatus(bid)
    
    // 使用Promise合并三个Promise事件 全部执行完成之后隐藏
    // 除了.all 还有.race竞争 最先完成加载的执行
    Promise.all([detail,comments,likeStatus])
    .then(res =>{
      console.log(res)
      this.setData({
        book:res[0],
        comments:res[1].comments,
        likeStatus:res[2].like_status,
        likeCount:res[2].fav_nums
      })
      wx.hideLoading()
    })

    // detail.then(res=>{
    //   // console.log(res)
    //   this.setData({
    //     book:res
    //   })
    // })
    
    // comments.then(res => {
    //   // console.log(res)
    //   this.setData({
    //     comments: res.comments
    //   })
    // })
    // likeStatus.then(res => {
    //   // console.log(res)
    //   this.setData({
    //     likeStatus: res.like_status,
    //     likeCount:res.fav_nums
    //   })
    // })
  },
  
  onLike(event) {
    let behavior = event.detail.behavior
    likeModel.like(behavior, this.data.book.id, 400)
  },
  onFakePost(event){
    this.setData({
      posting:true
    })
    console.log(this.data.comments)
  },
  onCancel(event){
    this.setData({
      posting: false
    })
  },
  onPost(event){
    const comment = event.detail.text || event.detail.value
    if(!comment){
      return
    }
    if( comment.length > 12){
      wx.showToast({
        title: '短评最多12个字',
        icon:'none'
      })
      return
    }

    bookModel.postComments(this.data.book.id,comment)
    .then(res =>{
      wx.showToast({
        title: '+1',
        icon: 'none'
      })
      this.data.comments.unshift({
        content:comment,
        nums:1
      })
      this.setData({
        comments: this.data.comments,
        posting: false
      })
    })
  },
})